package com.eastfair.certificate.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.eastfair.auth.vo.RoleVo;
import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.cache.certificate.CarRecordCacheKeyBuilder;
import com.eastfair.cache.certificate.CertificateCacheKeyBuilder;
import com.eastfair.certificate.dao.CarRecordMapper;
import com.eastfair.certificate.entity.CarRecord;
import com.eastfair.certificate.entity.Certificate;
import com.eastfair.certificate.entity.CertificateUser;
import com.eastfair.certificate.enumeration.CarRecordInOrOutEnum;
import com.eastfair.certificate.service.CarRecordService;
import com.eastfair.boot.service.SuperServiceImpl;

import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.model.CacheKeyBuilder;
import com.eastfair.database.mybatis.conditions.Wraps;
import com.eastfair.database.mybatis.conditions.query.QueryWrap;
import com.sun.jmx.snmp.Timestamp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

//import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.aop.framework.AopContext;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.annotation.annotation.cache.Cache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
//import com.baomidou.dynamic.datasource.annotation.DS;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.stream.Collectors;

import com.eastfair.certificate.vo.*;
import com.eastfair.certificate.dto.*;

/**
 * <p>
 * 业务实现类
 * 车辆出入证信息
 * </p>
 *
 * @author ligang
 * @date 2023-01-31
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class CarRecordServiceImpl extends SuperCacheServiceImpl<CarRecordMapper, CarRecord> implements CarRecordService {


    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(CarRecord model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setTeamId(ContextUtil.getTeamId());
        return R.successDef();
    }



    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<CarRecord> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<CarRecord> list(CarRecordDTO modelDTO, List<Long> ids) {
        return ((CarRecordService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{" +
                            "{'carCode', #args[0]?.carCode}," +
                            "{'inTime', #args[0]?.inTime}," +
                            "{'passTime', #args[0]?.passTime}," +
                            "{'parkId', #args[0]?.parkId}," +
                            "{'inOrOut', #args[0]?.inOrOut}," +
                            "{'guId', #args[0]?.guId}," +
                            "{'channelId', #args[0]?.channelId}," +
                            "{'channelName', #args[0]?.channelName}," +
                            "{'imagePath', #args[0]?.imagePath}," +
                            "{'isEnabled', #args[0]?.isEnabled}," +
                            "{'teamId', #args[0]?.teamId}," +
                            "{'id', #args[1]}" +
                            "}"))
    public List<CarRecord> listOfCache(CarRecordDTO modelDTO, List<Long> ids) {
        //查询
        CarRecord carRecord = new CarRecord();
        if (modelDTO != null) {
            BeanUtils.copyProperties(modelDTO, carRecord);
        }
        QueryWrap<CarRecord> wrapper = Wraps.q(carRecord);
        if (ids != null && !ids.isEmpty()) {
            wrapper.lambda().in(CarRecord::getId, ids);
        }
        //添加其他业务查询条件
        wrapper.lambda().eq(CarRecord::getIsDeleted, BusinessConstant.DELETE_NO);
        wrapper.lambda().ge(modelDTO.getInTimeOfGe() != null, CarRecord::getInTime, modelDTO.getInTimeOfGe());
        wrapper.lambda().le(modelDTO.getInTimeOfLe() != null, CarRecord::getInTime, modelDTO.getInTimeOfLe());
        wrapper.lambda().in(CollectionUtil.isNotEmpty(modelDTO.getCarCodes()), CarRecord::getCarCode, modelDTO.getCarCodes());

        List<CarRecord> modelList = list(wrapper);
        return modelList;
    }

    @Override
    public List<CarRecordVO> queryCar(CarRecordDTO modelDTO) {
        List<CarRecord> carRecordList = listOfCache(modelDTO, null);
        return doToVos(carRecordList);
    }

    public List<CarRecordVO> assmbileCarRecord(List<CarRecordVO> carRecordVOList, List<CertificateUser> certificateUserList) {
        if (CollectionUtil.isEmpty(carRecordVOList)) {
            return null;
        }
        List<CarRecordVO> result = new ArrayList<>();
        Map<String, List<CarRecordVO>> group2 = carRecordVOList.stream().collect(Collectors.groupingBy(CarRecordVO::getCarCode));

        for (CertificateUser certificateUser : certificateUserList) {
            CarRecordVO carRecordVO = new CarRecordVO();
            for (String carCode : group2.keySet()) {
                if (carCode.equals(certificateUser.getCarNumber())) {
                    //获取车辆所在的时间记录
                    CarRecordVO carRecordVO1 = assmbileCarRecord(group2.get(carCode).stream().filter(s -> s.getInTime().isAfter(certificateUser.getComeInTime())).collect(Collectors.toList()), certificateUser);
                    if (carRecordVO1 != null) {
                        result.add(carRecordVO1);
                    }
                    break;
                }
            }
        }
        return result;
    }


    public CarRecordVO assmbileCarRecord(List<CarRecordVO> userCarRecordList, CertificateUser certificateUser) {
        if (CollectionUtil.isEmpty(userCarRecordList)) {
            return null;
        }
        userCarRecordList = userCarRecordList.stream().filter(s -> s.getInTime().isAfter(certificateUser.getComeInTime())).sorted(Comparator.comparing(CarRecordVO::getInTime)).collect(Collectors.toList());
        CarRecordVO recordVO = new CarRecordVO();
        BeanUtils.copyProperties(userCarRecordList.get(0), recordVO);
        //找到开始时间
        LocalDateTime inTime = null;
        for (CarRecordVO carRecordVO : userCarRecordList) {
            if (CarRecordInOrOutEnum.IN.eq(carRecordVO.getInOrOut())) {
                inTime = carRecordVO.getInTime();
                break;
            }
        }
        //找到结束时间
        LocalDateTime outTime = null;
        for (CarRecordVO carRecordVO : userCarRecordList) {
            if (CarRecordInOrOutEnum.OUT.eq(carRecordVO.getInOrOut())) {
                outTime = carRecordVO.getInTime();
                break;
            }
        }
        recordVO.setInTime(inTime);
        recordVO.setOutTime(outTime);
        if (outTime != null && inTime != null) {
            ZoneId zone = ZoneId.systemDefault();
            Instant instant = inTime.atZone(zone).toInstant();
            long inTimeLong = instant.toEpochMilli();

            instant = outTime.atZone(zone).toInstant();
            long outTimeLong = instant.toEpochMilli();

            Long second = outTimeLong - inTimeLong;
            recordVO.setStayTimes(second);
        }
        return recordVO;
    }

    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public CarRecordVO doToVo(CarRecord model) {
        CarRecordVO modelVo = new CarRecordVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<CarRecordVO> doToVos(List<CarRecord> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<CarRecordVO> result = new ArrayList<>();
        for (CarRecord model : modelList) {
            result.add(doToVo(model));
        }
        return result;
    }

    @Override
    public CacheKeyBuilder getCacheKeyBuilder() {

        return new CarRecordCacheKeyBuilder();
    }
}
